
var WebStatus = new Class({
 Implements: Options,
 options: {
    timer: 5,
    count: 0,
    stopcount: 100,
    sites: [
     {site:'compuvest'},{site:'nexttag'},{site:'grabber'},{site:'shopping'},{site:'froogle'},
     {site:'bing'},{site:'cj'},{site:'bizrate'},{site:'cws'},{site:'onetime'},{site:'links'},
     {site:'amex'},{site:'oneway'},{site:'facebook'},{site:'amazon'},{site:'catch'},
     {site:'google01'},{site:'google02'},{site:'google03'},{site:'google04'},{site:'google05'},
     {site:'google06'},{site:'google07'},{site:'google08'},{site:'google09'},{site:'google10'},
     {site:'google11'},{site:'google12'},{site:'google13'},{site:'google14'},{site:'google15'},
     {site:'google16'},{site:'google17'},{site:'google18'},{site:'google19'},{site:'google20'},
     {site:'google21'},{site:'google22'},{site:'google23'},{site:'google24'},{site:'google25'},
     {site:'google26'},{site:'google27'},{site:'google28'},{site:'google29'},{site:'google30'},
     {site:'google31'},{site:'google32'},{site:'google33'},{site:'google34'},{site:'google35'}
    ]
 },
 dataB2B: '',
 initialize: function(elm) {
    var elem = document.id(elm);
    if(!elem) return;

    this.content = elem.getElement('div[id="content"]');
    if(!this.content) return;
    this.content.empty(); // clean panel

    this.getAdvert();

 },
 getAdvert: function() {

    new Request({
        url: '/Admin/webinfo/proxy',
        method: 'get',
        onComplete: function(resp) {
            this.data = eval('(' + resp + ')');

            this.b2b();
        }.bind(this),
        onFailure: function() {
        }
    }).send('id=com&nc=' + Date.now());
 },
 b2b: function() {

    new Request({
        url: '/Admin/webinfo/proxy',
        method: 'get',
        data: {'id': 'b2b', 'nc': Date.now()},
        onRequest: function() {
        },
        onComplete: function(resp) {
            this.dataB2B = eval('(' + resp + ')');

            this.fillHeadB2B();
        }.bind(this),
        onFailure: function() {
        }
    }).send();

 },
 fillHeadB2B: function() {
    this.fillHead();

    document.id('activeB2B').set('text', this.dataB2B.inf.active);
    document.id('todayVisitB2B').set('text', this.dataB2B.inf.todayVisit);
 },
 fillHead: function() {
   document.id('active').set('text', this.data.active);
   document.id('todayVisit').set('text', this.data.todayVisit);
   document.id('totalVisit').set('text', this.data.totalVisit);

   document.id('todayOrder').set('text', this.data.todayOrder);
   document.id('totalOrder').set('text', this.data.totalOrder);

   var newCust = this.data.todayAllCust - this.data.yesFillForm - this.data.notFillForm - this.data.reseller;
   var oldCust = this.data.todayOrder - newCust;
   var prcToday = newCust * 100 / this.data.todayAllCust;
   // All Customer
   document.id('todayCust').set('html', '<b>' + this.data.todayAllCust + '</b><br/>('
     + (prcToday).toFixed(2) + '%)');

    // Orders Filled
   document.id('filled').set('html', '<b>' + this.data.yesFillForm + '</b> (' + this.data.reseller + ')<br/>('
     + (prcToday - ((newCust - this.data.yesFillForm) * 100 / this.data.todayAllCust)).toFixed(2) + '%)');

   // Orders Registered
   document.id('regised').set('html', '<b>' + this.data.notFillForm + '</b><br/>('
     + (prcToday - ((newCust - this.data.notFillForm) * 100 / this.data.todayAllCust)).toFixed(2) + '%)');

   document.id('newCust').set('html', '<b>' + newCust + '</b>');

   document.id('oldCust').set('html', '<b>' + oldCust + '</b>');

   document.id('totalCust').set('html', '<b>' + this.data.totalCust + '</b>');

   this.makeAmazon();

   this.makeAdvertTable();
 },
 makeAmazon: function() {

    new Request({
        url: '/Admin/webstat/getFromMySQL',
        method: 'get',
        onRequest: function() {
            new Loader().show();
        },
        onComplete: function(resp) {
            var data = [];
            try {
                data = eval('(' + resp + ')');
            }
            catch(err) { alert('Error...\n' + err); return; }
            new Loader().hide();

            this.fillAmazon(data);
        }.bind(this)
    }).send('table=amazon&nc=' + Date.now());
 },
 fillAmazon: function(data) {

    var table = new Element('table[border=1]').adopt(
        new Element('tbody').adopt(
            new Element('tr[style=background-color:silver;]').adopt(
                new Element('th[style=width:60px;]'),
                new Element('th[text=login][style=width:60px;]'),
                new Element('th[text=shipping][style=width:60px;]'),
                new Element('th[text=orders][style=width:60px;]')
            ),
            new Element('tr[style=text-align:center;]').adopt(
                new Element('td[text=amazon]'),
                new Element('td[text=' + data.pg1 + ']'),
                new Element('td[html=' + data.pg2 + '<br/>' + numberFormat(data.pg2 * 100 / data.pg1) + '%]'),
                new Element('td[html=' + data.pg3 + '<br/>' + numberFormat(data.pg3 * 100 / data.pg1) + '%]')
            )
        )
    );
    this.content.adopt(table);
 },
 makeAdvertTable: function() {
    this.content.empty();

    var table = new Element('table#listData[rules=groups]').adopt(
        new Element('thead').adopt(
            new Element('tr').adopt(
                new Element('th.brdCol.w15[html=&nbsp;][style=cursor:default;]'),
                new Element('th.brdCol.w80[text=Advert]', {
                    'events':{
                        'mouseenter': function() {this.addClass('thHover');},
                        'mouseleave': function() {this.removeClass('thHover');}
                    }
                }),
                new Element('th.brdCol.w80[text=Hits]', {
                    'events':{
                        'mouseenter': function() {this.addClass('thHover');},
                        'mouseleave': function() {this.removeClass('thHover');}
                    }
                }),
                new Element('th.brdCol.w80[text=Orders]', {
                    'events':{
                        'mouseenter': function() {this.addClass('thHover');},
                        'mouseleave': function() {this.removeClass('thHover');}
                    }
                }),
                new Element('th.brdCol.w80[text=Rating]', {
                    'events':{
                        'mouseenter': function() {this.addClass('thHover');},
                        'mouseleave': function() {this.removeClass('thHover');}
                    }
                }),
                new Element('th.brdCol.w80[text=Amount]', {
                    'events':{
                        'mouseenter': function() {this.addClass('thHover');},
                        'mouseleave': function() {this.removeClass('thHover');}
                    }
                }),
                new Element('th.brdCol.w80[text=Average]', {
                    'events':{
                        'mouseenter': function() {this.addClass('thHover');},
                        'mouseleave': function() {this.removeClass('thHover');}
                    }
                })
            )
        )
    );

    var tbody,tr,td,hits=0,orders=0,amount=0.0,color=false,needGoogle=true,ghits=0,gorders=0,gamount=0.0,tagid;
    // body
    tbody = new Element('tbody');
    for(var i = 0; i < this.options.sites.length; i++) {
        var adv = this.getAdvertHost(this.options.sites[i].site);
        if(!adv.hits) continue;

        // if havn't orders no need show
        hits += adv.hits;
        orders += adv.orders;
        amount += adv.amount;

        // insert separator
        if(needGoogle && adv.host.indexOf('google') != -1) {
            needGoogle = false;

            td = new Element('td.imgCol').adopt(
                new Element('a.plus[href=javascript:;][html=&nbsp;]',{
                    'events': {
                        'click': function() {
                            if(this.hasClass('plus')) {
                                this.removeClass('plus').addClass('minus');

                                document.id('adv_google').setStyle('display', '');
                            }
                            else if(this.hasClass('minus')) {
                                this.removeClass('minus').addClass('plus');

                                document.id('adv_google').setStyle('display', 'none');
                            }
                        },
                        'focus': function() {this.blur();}
                    }
                })
            );

            table.adopt(
                tbody.adopt(
                    new Element('tr[style=background-color:#afbfff;]').adopt(
                        td,
                        new Element('td.brdCol.w80[html=<b>Google</b>]'),
                        new Element('td#ghits.brdCol.right.w80'),
                        new Element('td#gord.brdCol.right.w80'),
                        new Element('td#grat.brdCol.right.w80'),
                        new Element('td#gamt.brdCol.right.w80'),
                        new Element('td#gave.brdCol.right.w80')
                    )
                )
            );

            // make new tbody
            tbody = new Element('tbody#adv_google[style=display:none;]');
        }

        // sum for google
        if(!needGoogle) {
            ghits += adv.hits;
            gorders += adv.orders;
            gamount += adv.amount;
        }

        tagid = 'roc_' + i;
        tr = new Element('tr#' + tagid + '[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]', {
            'events': {
                'mouseenter': function() {this.addClass('rowHover');},
                'mouseleave': function() {this.removeClass('rowHover');}
            }
        })

        td = new Element('td.imgCol').adopt(
            new Element('a#i' + tagid + '.' + (adv.orders ? 'plus' : 'disalow') + '[href=javascript:;][html=&nbsp;][title=' + (adv.orders ? 'click to ' + adv.host : 'No orders!') + ']',{
                'events': {
                    'click': adv.orders ? this.getOrders.bind(this, adv.host, tagid) : function(){},
                    'focus': function() {this.blur();}
                }
            })
        );

        tbody.adopt(
            tr.adopt(
                td,
                new Element('td.brdCol.w80[html=<b>' + adv.host + '</b>]'),
                new Element('td.brdCol.right.w80[html=' + (adv.hits ? adv.hits : '&nbsp;') + ']'),
                new Element('td.brdCol.right.w80[html=' + (adv.orders ? adv.orders : '&nbsp;') + ']'),
                new Element('td.brdCol.right.w80[html=' + (adv.orders ? (adv.hits / adv.orders).toFixed(0) : '&nbsp;') + ']'),
                new Element('td.brdCol.right.w80[html=' + (adv.amount ? '$' + numberFormat(adv.amount) : '&nbsp;') + ']'),
                new Element('td.brdCol.right.w80[html=' + (adv.orders ? '$' + numberFormat(adv.amount / adv.orders) : '&nbsp;') + ']')
            )
        );

        if(adv.orders) {
            tbody.adopt(
                new Element('tr#x' + tagid + '[style=display:none;]').adopt(
                    new Element('td[html=&nbsp;]'),
                    new Element('td#d' + tagid + '[colspan=6][style=padding-top:0;]')
                )
            );
        }
    }// for
    table.adopt(tbody);

    table.adopt(
        new Element('tfoot').adopt(
            new Element('tr[style=text-align:right;]').adopt(
                new Element('th.brdCol.w15[html=&nbsp;]'),
                new Element('th.brdCol.w80[html=<b>Total :</b>]'),
                new Element('th.brdCol.w80[text=' + hits +']'),
                new Element('th.brdCol.w80[text=' + orders + ']'),
                new Element('th.brdCol.w80[text=' + (hits / orders).toFixed(0) + ']'),
                new Element('th.brdCol.w80[text=$' + numberFormat(amount) + ']'),
                new Element('th.brdCol.w80[text=$' + numberFormat(amount / orders) +']')
            )
        )
    );

    this.content.adopt(table);

    // set google stat
    document.id('ghits').set('html', '<b>' + ghits + '</b>');
    document.id('gord').set('html', '<b>' + (gorders ? gorders : '&nbsp;') + '</b>');
    document.id('grat').set('html', '<b>' + (gorders ? (hits / gorders).toFixed(0) : '&nbsp;') + '</b>');
    document.id('gamt').set('html', '<b>' + (gamount ? '$' + numberFormat(gamount) : '&nbsp;') + '</b>');
    document.id('gave').set('html', '<b>' + (gorders ? '$' + numberFormat(gamount / gorders) : '&nbsp;') + '</b>');

 },
 getAdvertHost: function(host) {
   for(var idx = 0; idx < this.data.adv.length; idx++) {
     if(host == this.data.adv[idx].n) {
       this.data.adv[idx].u = 1;
       return {host:host,hits:this.data.adv[idx].v,orders:this.data.adv[idx].o,amount:this.data.adv[idx].a,use:this.data.adv[idx].u};
     }
   }
   return {host:host,hits:0,orders:0,amount:0};
},
getOrders: function(host, tagid, ev) {
    ev.stop();
    this.curOrdersPage = 0;

    var xroc = document.id('x' + tagid);
    var droc = document.id('d' + tagid);
    if(ev.target.hasClass('plus')) {
        ev.target.removeClass('plus').addClass('minus');

        droc.empty();

        // create calendar and pager
        var calendar = new Element('td.left');
        var pager = new Element('td.right');
        new Element('table#pager').adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(
                    calendar,
                    pager
                )
            )
        ).inject(droc, 'top');

        this.ordersPager = new Pager({
            'tagid': pager,
            onNewpage: function(currentPage) {
                this.curOrdersPage = currentPage;

                this.orderRequest.send('table=advorders&adv=' + host + '&curPage=' + this.curOrdersPage + '&nc=' + Date.now());
            }.bind(this)
        });

        var tableTag = new Element('table#listOrder[style=line-height:8px;]').adopt(
            new Element('thead').adopt(
                new Element('tr').adopt(
                    new Element('th.brdCol.w15[html=&nbsp;]'),
                    new Element('th.brdCol.w120[text=Time]'),
                    new Element('th.brdCol.w120[text=No]'),
                    new Element('th.brdCol.w150[text=Name]'),
                    new Element('th.brdCol.w150[text=Email]'),
                    new Element('th.brdCol.w50[text=Orders]'),
                    new Element('th.brdCol.w50[text=Amount]')
                )
            ),
            new Element('tbody'),
            new Element('tfoot')
        );
        droc.adopt(tableTag);

        this.orderRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                ev.target.toggleClass('load');
            },
            onComplete: function(resp) {
                var data = '';
                try {
                    data = eval('(' + resp + ')');
                }
                catch(err) { alert('Error...' + err); return; }
                ev.target.toggleClass('load');

                this.makeOrdersTable(data, tableTag);
            }.bind(this)
        }).send('table=advorders&adv=' + host + '&curPage=' + this.curOrdersPage + '&nc=' + Date.now());

        xroc.set('styles', {'display':'','background-color':'#ffffff'});
    }
    else if(ev.target.hasClass('minus')) {
        ev.target.removeClass('minus').addClass('plus');

        xroc.setStyle('display', 'none');
    }
 },
 makeOrdersTable: function(data, table) {

    this.ordersPager.setData(data.curPage, data.cntPage, data.onPage, data.rows.length);

    var tbody,tr,order,color=false,td,i=0,sum=0.0,newCust=0;

    tbody = table.getElement('tbody');
    tbody.empty();

    for(; i < data.rows.length; i++) {
        order = data.rows[i];
        sum += order.amount;

        var oldCust = (order.orders > 1 ? true: false);
        tr = new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]', {
            'events': {
                'mouseenter': function() {this.addClass('rowHover');},
                'mouseleave': function() {this.removeClass('rowHover');}
            }
        });

        td = new Element('td.imgCol').adopt(
            new Element('a.open[href=javascript:;][html=&nbsp;][title=Open order]',{
                'events': {
                    'click': this.getOrder.bind(this, order.id),
                    'focus': function() {this.blur();}
                }
            })
        );

        tbody.adopt(
            tr.adopt(
                td,
                new Element('td.brdCol.center.w120[text=' + Date.parse(order.date).format('%b %d,%Y %H:%M:%S %a') + ']'),
                new Element('td.brdCol.center.w120[text=' + order.no + ']'),
                new Element('td.brdCol.w150[text=' + order.name + ']'),
                new Element('td.brdCol.w150[html=<tt style="color:navy;">' + order.email + '</tt>]'),
                new Element('td.brdCol.right.w50' + (oldCust ? '.red': '.green') + '[text=' + order.orders + ']'),
                new Element('td.brdCol.right.w50[text=$' + numberFormat(order.amount) + ']')
            )
        );

        newCust += (oldCust ? 0: 1);
    }// for

    var tfoot = table.getElement('tfoot');
    tfoot.empty().adopt(
        new Element('tr').adopt(
            new Element('th.tdFull[colspan=7][html=<p class="right">New: <b class="green">' + newCust +
                '</b> Old: <b class="red">' + (i - newCust) +
                '</b>&nbsp;&nbsp;&nbsp;Sum: <b>$' + numberFormat(sum) + '</b>&nbsp;</p>]')
        )
    );

 },
 getOrder: function(orderid, ev) {
    ev.stop();

    new ShowOrder(orderid, ev.target);
 }
});
